package top.ajun.mall.ware.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.ajun.common.constants.WareConstant;
import top.ajun.common.utils.PageUtils;
import top.ajun.common.utils.Query;
import top.ajun.mall.ware.dao.PurchaseDao;
import top.ajun.mall.ware.entity.PurchaseDetailEntity;
import top.ajun.mall.ware.entity.PurchaseEntity;
import top.ajun.mall.ware.service.PurchaseDetailService;
import top.ajun.mall.ware.service.PurchaseService;
import top.ajun.mall.ware.service.WareSkuService;
import top.ajun.mall.ware.vo.MergeVo;
import top.ajun.mall.ware.vo.PurchaseDoneVo;
import top.ajun.mall.ware.vo.PurchaseItemDoneVo;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
            new Query<PurchaseEntity>().getPage(params),
            Wrappers.query()
        );
        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnReceive(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
            new Query<PurchaseEntity>().getPage(params),
            Wrappers.<PurchaseEntity>lambdaQuery()
                .eq(PurchaseEntity::getStatus, "0").or()
                .eq(PurchaseEntity::getStatus, "1")
        );
        return new PageUtils(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();

        // 此采购单需要新建
        if (purchaseId == null) {
            PurchaseEntity purchase = new PurchaseEntity();
            purchase.setCreateTime(new Date());
            purchase.setUpdateTime(new Date());
            // 新建状态
            purchase.setStatus(WareConstant.PURCHASE_CREATED.getCode());
            this.save(purchase);
            purchaseId = purchase.getId();
        }

        // 确认采购单状态为 0 or 1 才进行合并
        PurchaseEntity purchaseEntity = this.getById(purchaseId);
        if (purchaseEntity.getStatus() == WareConstant.PURCHASE_CREATED.getCode() ||
            purchaseEntity.getStatus() == WareConstant.PURCHASE_ASSIGNED.getCode()) {
            // 合并到采购单
            List<Long> items = mergeVo.getItems();
            final Long selfPurchaseId = purchaseId;
            List<PurchaseDetailEntity> purchaseDetailList = items.stream().map(item -> {
                PurchaseDetailEntity purchaseDetail = new PurchaseDetailEntity();
                purchaseDetail.setId(item);
                purchaseDetail.setPurchaseId(selfPurchaseId);
                // 已分配状态
                purchaseDetail.setStatus(WareConstant.PURCHASE_DETAIL_ASSIGNED.getCode());
                return purchaseDetail;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(purchaseDetailList);

            // 更新采购单时间
            PurchaseEntity purchase = new PurchaseEntity();
            purchase.setId(purchaseId);
            purchase.setUpdateTime(new Date());
            this.updateById(purchase);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void receivePurchase(List<Long> ids) {
        // 确认当前采购单是新建或已分配状态
        List<PurchaseEntity> purchaseList = ids.stream()
            .map(this::getById)
            .filter(item -> item.getStatus() == WareConstant.PURCHASE_CREATED.getCode() ||
                item.getStatus() == WareConstant.PURCHASE_ASSIGNED.getCode())
            .peek(item -> {
                item.setStatus(WareConstant.PURCHASE_RECEIVED.getCode());
                item.setUpdateTime(new Date());
            })
            .collect(Collectors.toList());

        // 改变采购单的状态
        this.updateBatchById(purchaseList);

        // 改变采购项的状态
        purchaseList.forEach(item -> {
            List<PurchaseDetailEntity> purchaseDetailList = purchaseDetailService.listDetailByPurchaseId(item.getId());
            List<PurchaseDetailEntity> detailEntityList = purchaseDetailList.stream().map(detail -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(detail.getId());
                detailEntity.setStatus(WareConstant.PURCHASE_DETAIL_BUYING.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(detailEntityList);
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void donePurchase(PurchaseDoneVo doneVo) {
        // 改变采购项状态
        Long purchaseId = doneVo.getId();
        boolean flag = true;
        List<PurchaseItemDoneVo> items = doneVo.getItems();
        List<PurchaseDetailEntity> updates = new ArrayList<>();
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity purchaseDetail = new PurchaseDetailEntity();
            if (item.getStatus() == WareConstant.PURCHASE_DETAIL_HAS_ERROR.getCode()) {
                flag = false;
                purchaseDetail.setStatus(item.getStatus());
            } else {
                purchaseDetail.setStatus(WareConstant.PURCHASE_DETAIL_FINISHED.getCode());

                /*
                 将成功采购的进行入库:
                    skuId: 商品 id
                    wareId: 仓库 id
                    skuNum: 采购数量
                 */
                PurchaseDetailEntity entity = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum());
            }
            purchaseDetail.setId(item.getItemId());
            updates.add(purchaseDetail);
        }
        purchaseDetailService.updateBatchById(updates);

        // 改变采购单状态
        PurchaseEntity purchase = new PurchaseEntity();
        purchase.setId(purchaseId);
        purchase.setStatus(flag ? WareConstant.PURCHASE_FINISHED.getCode() : WareConstant.PURCHASE_HAS_ERROR.getCode());
        purchase.setUpdateTime(new Date());
        this.updateById(purchase);
    }

}